<?php

namespace Cron;

use Lib\Queue;

class Wxmsg extends \Cron\CronAbstract {

    public function main() {
        $beginTime = time();

        while(time() - $beginTime < 59) {
            $msg = Queue::pop('wxmsg');

            if(empty($msg)) {
                sleep(1);
                continue;
            }

            $this->send($msg);
        }
    }

    /**
     * @param array $content
     * @return bool
     */
    protected function send(array $content) {
        $content     = $this->parseContent($content);
        $accessToken = \Lib\Wechat::getInstance()->getToken();

        $http = new \Lib\Http();
        $http->setUrl("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken);
        $sendContent = \json_encode($content);
        $http->setPostFields($sendContent);
        $http->setTimeout(3);

        try {
          $http->send();
//            $returnMsg = json_decode($http->send());
        } catch(\Exception $e) {
//            $msg['status'] = false;
//            $returnMsg     = new \Lib\Std($msg);
        }

        return true;
    }

    /**
     * @param array $content
     * @return array
     */
    protected function parseContent(array $content) {
        $data = [];

        $data['touser']      = isset($content['touser']) ? $content['touser'] : null;
        $data['template_id'] = isset($content['template_id']) ? $content['template_id'] : null;
        $data['url']         = isset($content['url']) ? $content['url'] : null;
        $data['topcolor']    = isset($content['topcolor']) ? $content['topcolor'] : '#7B68EE';
        $data['data']        = isset($content['data']) ? $content['data'] : null;

        return $data;
    }
}
